package cn.datawin.cmppclient.sender.service;

import cn.datawin.bms.provider.entity.ProvProviderEntity;
import cn.datawin.bms.provider.entity.ProvProviderParamEntity;
import cn.datawin.bms.provider.redis.ProvProviderRedisDto;
import cn.datawin.cmppclient.sender.entity.Provider;
import cn.datawin.cmppclient.sender.entity.ProviderStatus;
import cn.datawin.cmppclient.service.ProvProviderParamService;
import cn.datawin.cmppclient.service.ProvProviderService;
import cn.datawin.common.core.util.RedisUtils;
import cn.datawin.constant.RedisPattern;
import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProviderService {


	private final ProvProviderService provProviderService;
	private final ProvProviderParamService provProviderParamService;

	public List<Provider> queryProviderListFromCache() {


		String redisPattern = RedisPattern.PROV_PROVIDER_CACHE.replace("%s", "*");
		//获取所有的keys

		int pageCount = 0;
		int page = 0;
		List<String> allKeys = new ArrayList<>();
		do{
			List<String> keys = RedisUtils.findKeysForPage(redisPattern,page,1000);
			pageCount = keys.size();
			if(pageCount>0){
				allKeys.addAll(keys);
				page++;
			}
		}while (pageCount>0);
		//根据keys查询所有的供应商
		List<Provider> result = new ArrayList<>();
		for (String key : allKeys) {
			ProvProviderRedisDto redisDto = RedisUtils.get(key);
			if(redisDto==null) continue;
			Provider provider = new Provider();
			provider.setNo(String.valueOf(redisDto.getId()));
			provider.setName(redisDto.getName());
			provider.setStatus_Code(redisDto.getStatus() == 1 ? ProviderStatus.START.toString() : ProviderStatus.STOP.toString());
			Map<String, String> paramsMap = redisDto.getParams();
			provider.setAccount(paramsMap.get("spId"));
			provider.setPassword(paramsMap.get("secret"));
			provider.setSp_Number(paramsMap.get("spCode"));
			provider.setIp(paramsMap.get("serverIp"));
			provider.setPort(Integer.valueOf(paramsMap.get("serverPort")));
			provider.setMax_Concurrent_Total(Integer.valueOf(paramsMap.get("connections")));
			provider.setSubmit_Speed(Integer.valueOf(paramsMap.get("submitSpeed")));
			provider.setProtocol_Type_Code("CMPP2");
			result.add(provider);
		}
		return result;
	}


	/**
	 * 获取可用的CMPP供应商列表
	 * @return 供应商列表
	 */
	public List<Provider> queryProviderList() {
		//获取cmpp供应商列表
		List<ProvProviderEntity> providerList = provProviderService.getCmppProviderList();
		if(CollUtil.isEmpty(providerList)) return CollUtil.newArrayList();
		//获取cmpp供应商参数列表
		List<Long> providerIdList = providerList.stream().map(ProvProviderEntity::getId).toList();
		List<ProvProviderParamEntity> paramList = provProviderParamService.getProviderParamList(providerIdList);
		if(CollUtil.isEmpty(paramList)) return CollUtil.newArrayList();
		//根据供应商ID列表查询供应商参数列表
		Map<Long, Map<String, String>> providerIdParamsMap = paramList.stream().collect(Collectors.groupingBy(ProvProviderParamEntity::getProviderId,
				Collectors.toMap(ProvProviderParamEntity::getFieldName, ProvProviderParamEntity::getFieldValue)));
		List<Provider> result = CollUtil.newArrayList();
		for (ProvProviderEntity provProvider : providerList) {
			Provider provider = new Provider();
			Long providerId = provProvider.getId();

			provider.setNo(String.valueOf(providerId));
			provider.setName(provProvider.getName());
			provider.setStatus_Code(provProvider.getStatus() == 1 ? ProviderStatus.START.toString() : ProviderStatus.STOP.toString());

			Map<String, String> paramsMap = providerIdParamsMap.get(providerId);

			provider.setAccount(paramsMap.get("spId"));
			provider.setPassword(paramsMap.get("secret"));
			provider.setSp_Number(paramsMap.get("spCode"));
			provider.setIp(paramsMap.get("serverIp"));
			provider.setPort(Integer.valueOf(paramsMap.get("serverPort")));
			provider.setMax_Concurrent_Total(Integer.valueOf(paramsMap.get("connections")));
			provider.setSubmit_Speed(Integer.valueOf(paramsMap.get("submitSpeed")));
			provider.setProtocol_Type_Code("CMPP2");
//			if (provProvider.getApiProgramId().equals(1L)) {
//				provider.setProtocol_Type_Code(ProtocolType.CMPP2.toString());
//			} else {
//				provider.setProtocol_Type_Code(ProtocolType.CMPP3.toString());
//			}

			result.add(provider);
		}
		return result;
	}


	public String getProviderStatusByNo(String providerNo) {
		ProvProviderEntity provProvider = provProviderService.getById(Long.valueOf(providerNo));

		if (provProvider != null && provProvider.getStatus() != null && provProvider.getStatus() == 1) {
			return ProviderStatus.START.toString();
		}
		return ProviderStatus.STOP.toString();
	}

	public void setProviderStatusByNo(String providerNo) {
		ProvProviderEntity provProvider = new ProvProviderEntity();
		provProvider.setId(Long.valueOf(providerNo));
		provProvider.setStatus(2);
		provProviderService.updateById(provProvider);
	}

	public void insertEarlyWarning(Document document) {
//		mongoHelper.getCollection("early_warning").insertOne(document);
	}

	public String getProviderStatusByNoFromCache(String providerNo) {
		ProvProviderRedisDto provProviderRedisDto = RedisUtils.get(providerNo);
		if (provProviderRedisDto != null && provProviderRedisDto.getStatus() != null && provProviderRedisDto.getStatus() == 1) {
			return ProviderStatus.START.toString();
		}
		return ProviderStatus.STOP.toString();
	}
    /*@Resource
    private ResProviderService resProviderService;
    @Resource
    private ResProviderParameterService resProviderParameterService;
    @Resource
    private MongoHelper mongoHelper;

    public List<Provider> queryProviderList() {
        List<Provider> result = new ArrayList<>();

        List<ResProvider> resProviderList = resProviderService.getValidResProviderList();
        if (CollectionUtils.isEmpty(resProviderList)) {
            return result;
        }

        List<Long> providerIdList = resProviderList.stream().map(o -> o.getProviderId()).collect(Collectors.toList());

        List<ResProviderParameter> resProviderParameterList = resProviderParameterService.getResProviderParameterList(providerIdList);

        Map<Long, Map<String, String>> resProviderIdParamsMap = resProviderParameterList.stream().collect(Collectors.groupingBy(ResProviderParameter::getProviderId,
                Collectors.toMap(ResProviderParameter::getArgName, ResProviderParameter::getArgValue)));

        for (ResProvider resProvider : resProviderList) {
            Provider provider = new Provider();
            Long resProviderId = resProvider.getProviderId();

            provider.setNo(String.valueOf(resProviderId));
            provider.setName(resProvider.getProviderName());
            provider.setStatus_Code(resProvider.getStatus() == 1 ? ProviderStatus.START.toString() : ProviderStatus.STOP.toString());

            Map<String, String> paramsMap = resProviderIdParamsMap.get(resProviderId);

            provider.setAccount(paramsMap.get("SP_Id"));
            provider.setPassword(paramsMap.get("secret"));
            provider.setSp_Number(paramsMap.get("SP_Code"));
            provider.setIp(paramsMap.get("serverIp"));
            provider.setPort(Integer.valueOf(paramsMap.get("serverPort")));
            provider.setMax_Concurrent_Total(Integer.valueOf(paramsMap.get("connections")));
            provider.setSubmit_Speed(Integer.valueOf(paramsMap.get("submitSpeed")));
            if (resProvider.getApiProgramId().equals(1L)) {
                provider.setProtocol_Type_Code(ProtocolType.CMPP2.toString());
            } else {
                provider.setProtocol_Type_Code(ProtocolType.CMPP3.toString());
            }

            result.add(provider);
        }

        return result;
    }

    public String getProviderStatusByNo(String providerNo) {
        ResProvider resProvider = resProviderService.getById(Long.valueOf(providerNo));

        if (resProvider != null && resProvider.getStatus() != null && resProvider.getStatus() == 1) {
            return ProviderStatus.START.toString();
        }

        return ProviderStatus.STOP.toString();
    }

    public void setProviderStatusByNo(String providerNo) {
        ResProvider resProvider = new ResProvider();
        resProvider.setProviderId(Long.valueOf(providerNo));
        resProvider.setStatus(2);
        resProviderService.updateById(resProvider);
    }

    public void insertEarlyWarning(Document document) {
        mongoHelper.getCollection("early_warning").insertOne(document);
    }*/

}
